<template>
  <div class="user-info-setting">
    <el-row :gutter="20">
      <!-- 左侧：基本信息卡片 -->
      <el-col :span="16">
        <!-- 基本信息展示卡片 -->
        <el-card class="info-card" v-if="!isEditing">
          <template #header>
            <div class="card-header">
              <span>基本信息</span>
              <div class="header-buttons">
                <el-button type="primary" @click="startEdit">修改信息</el-button>
                <el-button type="warning" @click="openPasswordDialog">修改密码</el-button>
              </div>
            </div>
          </template>
          
          <div class="info-content">
            <div class="info-section">
              <h3 class="section-title">个人资料</h3>
              <div class="info-item">
                <span class="label">用户名：</span>
                <span class="value">{{ userInfo.username }}</span>
              </div>
              <div class="info-item">
                <span class="label">邮箱：</span>
                <span class="value">{{ userInfo.email }}</span>
              </div>
              <div class="info-item">
                <span class="label">手机号：</span>
                <span class="value">{{ userInfo.phone }}</span>
              </div>
              <div class="info-item">
                <span class="label">注册时间：</span>
                <span class="value">{{ formatDate(userInfo.registerTime) }}</span>
              </div>
              <div class="info-item">
                <span class="label">最近登录：</span>
                <span class="value">{{ formatDate(userInfo.lastLogin) }}</span>
              </div>
            </div>

            <el-divider />

          </div>
        </el-card>

        <!-- 信息修改表单 -->
        <el-card class="edit-card" v-if="isEditing">
          <template #header>
            <div class="card-header">
              <span>修改个人信息</span>
            </div>
          </template>
          
          <el-form 
            ref="userFormRef"
            :model="userForm"
            :rules="rules"
            label-width="100px"
            class="user-form">
            
            <el-form-item label="用户名" prop="username">
              <el-input v-model="userForm.username" placeholder="请输入用户名"></el-input>
            </el-form-item>
            
            <el-form-item label="邮箱" prop="email">
              <el-input v-model="userForm.email" placeholder="请输入邮箱"></el-input>
            </el-form-item>
            
            <el-form-item label="手机号" prop="phone">
              <el-input v-model="userForm.phone" placeholder="请输入手机号"></el-input>
            </el-form-item>
            
            <el-form-item>
              <el-button type="primary" @click="updateUserInfo">保存修改</el-button>
              <el-button @click="cancelEdit">取消</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧：头像和通知设置 -->
      <el-col :span="8">
        <!-- 头像设置卡片 -->
        <el-card class="avatar-card">
          <template #header>
            <div class="card-header">
              <span>头像设置</span>
            </div>
          </template>
          
          <div class="avatar-content">
            <el-avatar 
              :size="120" 
              :src="userInfo.avatar || defaultAvatar"
              class="current-avatar" />
            
            <el-upload
              class="avatar-uploader"
              :action="null"
              :http-request="handleAvatarUpload"
              :show-file-list="false"
              :before-upload="beforeAvatarUpload">
              <el-button type="primary" class="upload-btn">更换头像</el-button>
            </el-upload>
            
            <p class="upload-tip">支持 jpg、png、gif 格式，大小不超过 2MB</p>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 添加密码修改弹窗 -->
    <el-dialog
      v-model="passwordDialog.visible"
      title="修改密码"
      width="30%"
      class="password-dialog">
      <el-form 
        ref="passwordFormRef"
        :model="passwordForm"
        :rules="passwordRules"
        label-width="100px"
        class="password-form">
        
        <el-form-item label="原密码" prop="oldPassword">
          <el-input 
            v-model="passwordForm.oldPassword" 
            type="password" 
            placeholder="请输入原密码"
            show-password></el-input>
        </el-form-item>
        
        <el-form-item label="新密码" prop="newPassword">
          <el-input 
            v-model="passwordForm.newPassword" 
            type="password" 
            placeholder="请输入新密码"
            show-password></el-input>
        </el-form-item>
        
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input 
            v-model="passwordForm.confirmPassword" 
            type="password" 
            placeholder="请再次输入新密码"
            show-password></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="passwordDialog.visible = false">取消</el-button>
          <el-button type="primary" @click="updatePassword">确认修改</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../../../store/UserStore'

export default {
  name: 'UserinfoSetting',
  setup() {
    const userStore = useUserStore()
    const isEditing = ref(false)
    const defaultAvatar = '/assets/default-avatar.png'
    const passwordFormRef = ref(null)
    const userFormRef = ref(null)
    
    const userInfo = reactive({
      username: '',
      email: '',
      phone: '',
      registerTime: '',
      lastLogin: '',
      avatar: ''
    })

    const userForm = reactive({
      username: '',
      email: '',
      phone: ''
    })

    const passwordForm = reactive({
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    })

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      email: [
        { required: true, message: '请输入邮箱地址', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
      ],
      phone: [
        { required: true, message: '请输入手机号', trigger: 'blur' },
        { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
      ]
    }

    const passwordRules = {
      oldPassword: [
        { required: true, message: '请输入原密码', trigger: 'blur' }
      ],
      newPassword: [
        { required: true, message: '请输入新密码', trigger: 'blur' }
      ],
      confirmPassword: [
        { required: true, message: '请再次输入新密码', trigger: 'blur' },
        {
          validator: (rule, value, callback) => {
            if (value !== passwordForm.newPassword) {
              callback(new Error('两次输入的密码不一致'))
            } else {
              callback()
            }
          },
          trigger: 'blur'
        }
      ]
    }

    const passwordDialog = ref({
      visible: false
    })

    // 获取用户信息
    const getUserInfo = async () => {
      try {
        // 从状态机获取用户ID
        const userId = userStore.userInfo?.userId
        console.log('=== 开始获取用户信息 ===')
        console.log('当前用户ID:', userId)
        console.log('当前用户状态:', userStore.userInfo)
        
        if (!userId) {
          console.error('未获取到用户ID，当前用户状态:', userStore.userInfo)
          ElMessage.error('未获取到用户ID，请重新登录')
          return
        }
        
        // 从接口获取最新用户信息
        const url = `http://localhost:8080/user/user_find/${userId}`
        console.log('请求URL:', url)
        
        const response = await axios.get(url)
        console.log('获取到的用户信息:', response.data)
        
        if (!response.data) {
          console.error('获取用户信息失败：数据为空')
          ElMessage.error('获取用户信息失败：数据为空')
          return
        }

        const data = response.data
        // 确保数据不为空，并处理可能的null值
        const userData = {
          username: data.username || '',
          email: data.email || '',
          phone: data.phone || '',
          registerTime: data.registerTime || '',
          lastLogin: data.lastLogin || '',
          avatar: data.avatar || defaultAvatar,
          realName: data.realName || '',
          gender: data.gender || 0,
          birthDate: data.birthDate || '',
          status: data.status || 1
        }
        
        console.log('处理后的用户数据:', userData)
        
        // 更新本地状态
        Object.assign(userInfo, userData)
        console.log('更新后的本地状态:', userInfo)
        
        // 更新状态机
        userStore.userInfo = { ...userStore.userInfo, ...userData }
        console.log('更新后的状态机:', userStore.userInfo)
        
        console.log('=== 用户信息获取完成 ===')
      } catch (error) {
        console.error('获取用户信息错误:', error)
        console.error('错误详情:', {
          message: error.message,
          response: error.response,
          request: error.request
        })
        ElMessage.error('获取用户信息失败：' + (error.response?.data || error.message))
      }
    }

    // 开始编辑
    const startEdit = () => {
      console.log('开始编辑，当前用户信息:', userInfo)
      Object.assign(userForm, {
        username: userInfo.username || '',
        email: userInfo.email || '',
        phone: userInfo.phone || ''
      })
      isEditing.value = true
    }

    // 取消编辑
    const cancelEdit = () => {
      console.log('取消编辑，重置表单')
      Object.assign(userForm, {
        username: userInfo.username || '',
        email: userInfo.email || '',
        phone: userInfo.phone || ''
      })
      isEditing.value = false
    }

    // 更新用户信息
    const updateUserInfo = async () => {
      try {
        if (!userFormRef.value) return
        await userFormRef.value.validate(async (valid) => {
          if (valid) {
            const response = await axios.post('/user/user_update', {
              userId: userStore.userInfo.userId,
              ...userForm
            })
            if (response.data > 0) {
              ElMessage.success('个人信息更新成功')
              Object.assign(userInfo, userForm)
              // 更新状态机中的用户信息
              userStore.userInfo = { ...userStore.userInfo, ...userForm }
              isEditing.value = false
            } else {
              ElMessage.error('个人信息更新失败')
            }
          }
        })
      } catch (error) {
        ElMessage.error('更新失败：' + error.message)
      }
    }

    // 打开密码修改弹窗
    const openPasswordDialog = () => {
      passwordDialog.value.visible = true
      // 重置表单
      passwordForm.oldPassword = ''
      passwordForm.newPassword = ''
      passwordForm.confirmPassword = ''
    }

    // 更新密码
    const updatePassword = async () => {
      try {
        if (!passwordFormRef.value) return
        await passwordFormRef.value.validate(async (valid) => {
          if (valid) {
            const response = await axios.post('http://localhost:8080/user/update_password', {
              userId: userStore.userInfo.userId,
              oldPassword: passwordForm.oldPassword,
              newPassword: passwordForm.newPassword
            })
            
            if (response.data === "密码修改成功") {
              ElMessage.success('密码修改成功')
              passwordDialog.value.visible = false
              passwordForm.oldPassword = ''
              passwordForm.newPassword = ''
              passwordForm.confirmPassword = ''
            } else {
              ElMessage.error(response.data || '密码修改失败')
            }
          }
        })
      } catch (error) {
        console.error('修改密码失败:', error)
        ElMessage.error('修改失败：' + (error.response?.data || error.message))
      }
    }

    // 自定义上传方法
    const handleAvatarUpload = async (options) => {
      try {
        console.log('=== 开始头像上传流程 ===')
        console.log('当前状态机状态:', userStore.userInfo)
        console.log('当前本地状态:', userInfo)
        
        const formData = new FormData()
        formData.append('file', options.file)
        formData.append('userId', userStore.userInfo.userId)

        console.log('准备发送的数据:', {
          userId: userStore.userInfo.userId,
          fileName: options.file.name,
          fileType: options.file.type,
          fileSize: options.file.size
        })

        // 上传文件到后端
        console.log('开始上传文件到后端...')
        const uploadResponse = await axios.post('http://localhost:8080/user/upload_avatar', formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          },
          onUploadProgress: (progressEvent) => {
            const percent = Math.round((progressEvent.loaded * 100) / progressEvent.total)
            options.onProgress({ percent })
          }
        })

        console.log('文件上传响应:', uploadResponse)
        if (uploadResponse.data) {
          // 获取返回的文件名
          const fileName = uploadResponse.data
          console.log('服务器返回的文件名:', fileName)
          
          // 构建完整的头像路径
          const avatarPath = `/avatars/${fileName}`
          console.log('构建的完整头像路径:', avatarPath)
          
          // 调用设置头像接口更新数据库
          console.log('开始更新数据库头像路径...')
          const setAvatarResponse = await axios.post('http://localhost:8080/user/set_avatar', {
            userId: userStore.userInfo.userId,
            avatar: avatarPath
          }, {
            headers: {
              'Content-Type': 'application/json'
            }
          })
          
          console.log('数据库更新响应:', setAvatarResponse)
          if (setAvatarResponse.data === '头像路径更新成功') {
            console.log('数据库更新成功，开始更新本地状态...')
            
            // 更新本地状态
            userInfo.avatar = avatarPath
            console.log('本地状态更新后:', userInfo)
            
            // 更新状态机中的头像
            console.log('开始更新状态机...')
            console.log('更新前状态机状态:', userStore.userInfo)
            
            // 同时更新 userInfo 和 avatarUrl
            userStore.$patch({
              userInfo: { ...userStore.userInfo, avatar: avatarPath },
              avatarUrl: avatarPath
            })
            
            console.log('状态机更新后:', userStore.userInfo)
            
            // 验证状态机更新
            console.log('验证状态机更新:')
            console.log('- 状态机中的头像路径:', userStore.userInfo.avatar)
            console.log('- 本地状态中的头像路径:', userInfo.avatar)
            
            ElMessage.success('头像更新成功')
            options.onSuccess(avatarPath)
            
            // 强制更新视图
            console.log('等待视图更新...')
            await nextTick()
            console.log('视图更新完成')
            
            console.log('=== 头像上传流程完成 ===')
          } else {
            console.error('数据库更新失败:', setAvatarResponse.data)
            throw new Error('设置头像失败：' + setAvatarResponse.data)
          }
        } else {
          console.error('上传响应数据为空')
          throw new Error('上传失败：服务器返回数据为空')
        }
      } catch (error) {
        console.error('=== 头像上传失败 ===')
        console.error('错误详情:', {
          message: error.message,
          response: error.response?.data,
          status: error.response?.status,
          headers: error.response?.headers
        })
        
        let errorMessage = '头像上传失败'
        if (error.response?.data) {
          errorMessage += '：' + error.response.data
        } else if (error.message) {
          errorMessage += '：' + error.message
        }
        
        ElMessage.error(errorMessage)
        options.onError(error)
      }
    }

    // 头像上传前的验证
    const beforeAvatarUpload = (file) => {
      console.log('开始验证文件:', file)
      const isJPG = file.type === 'image/jpeg'
      const isPNG = file.type === 'image/png'
      const isGIF = file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG && !isPNG && !isGIF) {
        ElMessage.error('上传头像图片只能是 JPG、PNG 或 GIF 格式!')
        return false
      }
      if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!')
        return false
      }
      return true
    }

    // 格式化日期
    const formatDate = (date) => {
      if (!date) return '暂无记录'
      try {
        const dateObj = new Date(date)
        if (isNaN(dateObj.getTime())) return '暂无记录'
        return dateObj.toLocaleString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit',
          hour12: false
        })
      } catch (error) {
        console.error('日期格式化错误：', error)
        return '暂无记录'
      }
    }

    onMounted(() => {
      getUserInfo()
    })

    return {
      isEditing,
      userInfo,
      userForm,
      passwordForm,
      rules,
      passwordRules,
      defaultAvatar,
      userFormRef,
      passwordFormRef,
      startEdit,
      cancelEdit,
      updateUserInfo,
      updatePassword,
      formatDate,
      beforeAvatarUpload,
      handleAvatarUpload,
      userStore,
      // 密码修改相关
      passwordDialog,
      openPasswordDialog
    }
  }
}
</script>

<style scoped>
.user-info-setting {
  padding: 0 0 20px 0;  /* 确保顶部内边距为0，保留其他方向的内边距 */
  margin-top: 0 !important;
  max-width: 1200px;
  margin-left: auto; /* 水平居中 */
  margin-right: auto; /* 水平居中 */
}

.info-card,
.edit-card,
.avatar-card {
  margin-bottom: 20px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  background-color: #fff;  /* 确保卡片背景为白色 */
}

/* 确保第一个卡片没有顶部边距 */
.info-card:first-child,
.edit-card:first-child {
  margin-top: 0;
}

/* 移除 ElCard 默认的 padding，然后对内部内容块添加自定义 padding */
:deep(.el-card__body) {
  padding: 20px !important; /* 恢复 ElCard 默认的内边距 */
}

.info-content {
  /* 为实际内容添加 padding，如果需要覆盖 el-card__body 默认值 */
}

.user-form,
.password-form {
  max-width: 500px;
  margin: 0 auto;
  /* 为表单添加 padding，如果需要覆盖 el-card__body 默认值 */
}

.avatar-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  /* 为头像内容添加 padding，如果需要覆盖 el-card__body 默认值 */
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.header-buttons {
  display: flex;
  gap: 10px;
}

.info-section {
  margin-bottom: 24px;
}

.section-title {
  font-size: 18px;
  color: #303133;
  margin: 0 0 16px;
  font-weight: 600;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.info-item {
  display: flex;
  margin-bottom: 15px;
  font-size: 15px;
  line-height: 1.5;
}

.info-item .label {
  width: 100px;
  color: #606266;
  font-weight: 500;
}

.info-item .value {
  flex: 1;
  color: #303133;
}

.current-avatar {
  margin-bottom: 20px;
  border: 4px solid #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.upload-btn {
  margin-bottom: 10px;
}

.upload-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 10px;
}

.el-button {
  margin-right: 10px;
}

@media (max-width: 768px) {
  .user-info-setting {
    padding: 10px;
  }

  .info-item {
    flex-direction: column;
  }

  .info-item .label {
    margin-bottom: 5px;
  }
}

.el-divider {
  margin: 24px 0;
}

/* 响应式调整 */
@media (max-width: 768px) {
  .user-info-setting {
    padding: 10px;
  }

  .info-item {
    flex-direction: column;
  }

  .info-item .label {
    margin-bottom: 5px;
  }
}
</style>
